package servlet;

import bean.Menu;
import bean.MenuLevelOne;
import bean.MenuLevelTwo;
import bean.User;
import dao.UserDao;
import dao.impl.UserDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MenuServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        UserDao userDao=new UserDaoImpl();
        List<Menu> menus = userDao.menu(user.getId());
        List<MenuLevelOne> menuLevelOnes = new ArrayList<>();
        for (Menu menu :
                menus) {
            if (menu.getParentId().equals(0)) {
                MenuLevelOne menuLevelOne = new MenuLevelOne();
                menuLevelOne.setId(menu.getId());
                menuLevelOne.setMenuName(menu.getMenuName());
                menuLevelOnes.add(menuLevelOne);
            } else {
                for (MenuLevelOne m :
                        menuLevelOnes) {
                    if (m.getId().equals(menu.getParentId())) {
                        MenuLevelTwo menuLevelTwo = new MenuLevelTwo();
                        menuLevelTwo.setId(menu.getId());
                        menuLevelTwo.setMenuName(menu.getMenuName());
                        menuLevelTwo.setTarget(menu.getTarget());
                        menuLevelTwo.setUrl(menu.getUrl());
                        menuLevelTwo.setParentld(menu.getParentId());
                        menuLevelTwo.setIcon(menu.getIcon());
                        m.getChilds().add(menuLevelTwo);
                    }
                }
            }
        }
        session.setAttribute("menus", menuLevelOnes);
        resp.sendRedirect("main.html");
    }
}
